package com.chat.common.websocket;

import cn.hutool.core.net.url.UrlBuilder;
import cn.hutool.http.HttpUtil;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.HttpContent;
import io.netty.handler.codec.http.HttpObject;
import io.netty.handler.codec.http.HttpRequest;
import org.apache.commons.lang3.StringUtils;

import java.net.InetSocketAddress;
import java.util.Optional;

public class MyConnectHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (msg instanceof HttpRequest) {
            HttpRequest request = (HttpRequest) msg;
            String uri = request.uri();
            UrlBuilder urlBuilder = UrlBuilder.ofHttp(uri);
            Optional<String> token = Optional.ofNullable(urlBuilder)
                    .map(UrlBuilder::getQuery)
                    .map(t -> t.get("token"))
                    .map(CharSequence::toString);
            //如果token 存在 将token 先存入 netty
            token.ifPresent(s -> NettyUtil.setAttr(ctx.channel(), NettyUtil.TOKEN, s));
            request.setUri(urlBuilder.getPath().toString());
            //获取用户的ip
            String ip = request.headers().get("X-Real-IP");
            if(StringUtils.isBlank(ip)){
                ip = ((InetSocketAddress)ctx.channel().remoteAddress()).getAddress().getHostAddress();
            }
            //保存到channel中
            NettyUtil.setAttr(ctx.channel(),NettyUtil.IP,ip);
            //用完以后 移除这个handler
            ctx.pipeline().remove(this);
            ctx.fireChannelRead(request);
        }else
        {
            ctx.fireChannelRead(msg);
        }

}
}
